package org.csu.mypetstore_ssm.controller;

import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.csu.mypetstore_ssm.tool.MD5Util;
import org.csu.mypetstore_ssm.domain.Account;
import org.csu.mypetstore_ssm.persistence.AccountMapper;
import org.csu.mypetstore_ssm.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@Controller
public class AccountFormController {

    @Autowired
    private HttpSession httpSession;
    String message;

    @Autowired
    AccountService accountService;

    //获得登录请求并检验
    @PostMapping("/signOn")
    @ResponseBody
    public String signOnPlease(Model model, @RequestParam(value = "userName") String userName ,
                             @RequestParam(value = "password") String password,
                             HttpServletResponse response
    ) throws IOException {
        System.out.println(userName);
        System.out.println(password);
        //根据用户名与密码获取用户完整信息
        Account loginAccount = accountService.getAccountByUsernameAndPassword(userName,MD5Util.string2MD5(password));
        //获取account成功
        if(loginAccount != null){
            //用户信息加入session
            httpSession.setAttribute("loginAccount",loginAccount);
            //返回到主页面
            return "";
        //获取失败
        }else {
            //错误信息
            String message = "密码或账号填写有误";
            //并填入错误信息
            model.addAttribute("errorMSG",message);
            //返回登录页面重新登录
            return message;
        }
    }

    //创建新用户
    @PostMapping("/newAccount")
    @ResponseBody
    public String newAccount(Model model,
                             @RequestParam(value = "address1", required = false) String address1,
                             @RequestParam(value = "address2", required = false) String address2,
                             @RequestParam(value = "city", required = false) String city,
                             @RequestParam(value = "country", required = false) String country,
                             @RequestParam(value = "email", required = false) String email,
                             @RequestParam(value = "bannerOption", required = false) String bannerOption,
                             @RequestParam(value = "favouriteCategoryId", required = false) String favouriteCategoryId,
                             @RequestParam(value = "password", required = false) String password,
                             @RequestParam(value = "repeatedPassword", required = false) String repeatedPassword,
                             @RequestParam(value = "firstName", required = false) String firstName,
                             @RequestParam(value = "languagePreference", required = false) String languagePreference,
                             @RequestParam(value = "lastName", required = false) String lastName,
                             @RequestParam(value = "listOption", required = false) String listOption,
                             @RequestParam(value = "phone", required = false) String phone,
                             @RequestParam(value = "state", required = false) String state,
                             @RequestParam(value = "userName", required = false) String userName,
                             @RequestParam(value = "zip", required = false) String zip,
                             @RequestParam(value = "emailCaptcha", required = false) String emailCaptcha,
                             @SessionAttribute(value = "emailCode", required = false) String emailCode,
                             HttpServletResponse response
                             ) throws IOException {

        Account account = new Account();
        account.setAddress1(address1);
        account.setAddress2(address2);
        account.setBannerName("<image src=\"images/banner_"+favouriteCategoryId.toLowerCase()+".gif\">");
        account.setCity(city);
        account.setCountry(country);
        account.setEmail(email);


        if(bannerOption != null){
            if(bannerOption.equals("1")){
                account.setBannerOption(true);
            }else {
                account.setBannerOption(false);
            }
        }

        if(listOption != null){
            if(listOption.equals("1")){
                account.setListOption(true);
            }else {
                account.setListOption(false);
            }
        }

        account.setFavouriteCategoryId(favouriteCategoryId);
        account.setPassword(MD5Util.string2MD5(password));
        account.setFirstName(firstName);
        account.setLanguagePreference(languagePreference);
        account.setLastName(lastName);
        account.setPhone(phone);
        account.setState(state);
        account.setUsername(userName);
        account.setZip(zip);

        if(!validate(address1,
                address2,
                city,
                country,
                email,
                favouriteCategoryId,
                password,
                repeatedPassword,
                firstName,
                languagePreference,
                lastName,
                phone,
                state,
                userName,
                zip)) {
            model.addAttribute("newAccountMSG", this.message);
            httpSession.setAttribute("errorAccount", account);
            return this.message;
//        } else if (emailCaptcha == null || emailCaptcha == null || !emailCode.equals(emailCaptcha)) {
//            model.addAttribute("newAccountMSG", "验证码错误");
//            httpSession.setAttribute("errorAccount",account);
//            return "account/newAccount";
        }else if (password == null || password.equals("")){
            model.addAttribute("newAccountMSG", "密码为空");
            httpSession.setAttribute("errorAccount", account);
            return this.message;
        }else {
            accountService.insertAccount(account);

            httpSession.setAttribute("loginAccount",account);
            response.sendRedirect("/main");
        }
        return "???";
    }

    //修改用户信息
    @PostMapping("/editeAccount")
    public String editeAccount(Model model,
                             @RequestParam(value = "address1", required = false) String address1,
                             @RequestParam(value = "address2", required = false) String address2,
                             @RequestParam(value = "city", required = false) String city,
                             @RequestParam(value = "country", required = false) String country,
                             @RequestParam(value = "email", required = false) String email,
                             @RequestParam(value = "bannerOption", required = false) String bannerOption,
                             @RequestParam(value = "favouriteCategoryId", required = false) String favouriteCategoryId,
                             @RequestParam(value = "password", required = false) String password,
                             @RequestParam(value = "repeatPassword", required = false) String repeatedPassword,
                             @RequestParam(value = "firstName", required = false) String firstName,
                             @RequestParam(value = "languagePreference", required = false) String languagePreference,
                             @RequestParam(value = "lastName", required = false) String lastName,
                             @RequestParam(value = "listOption", required = false) String listOption,
                             @RequestParam(value = "phone", required = false) String phone,
                             @RequestParam(value = "state", required = false) String state,
                             @RequestParam(value = "userName", required = false) String userName,
                             @RequestParam(value = "zip", required = false) String zip,
                             @SessionAttribute("loginAccount") Account loginAccount
    ){
        if(!validate(address1,
                    address2,
                    city,
                    country,
                    email,
                    favouriteCategoryId,
                    password,
                    repeatedPassword,
                    firstName,
                    languagePreference,
                    lastName,
                    phone,
                    state,
                    userName,
                    zip)){
            model.addAttribute("errorMSG",this.message);
            return("account/editeAccount");
        }else {
            loginAccount.setAddress1(address1);
            loginAccount.setAddress2(address2);
            loginAccount.setCity(city);
            loginAccount.setCountry(country);
            loginAccount.setEmail(email);

            if(bannerOption != null){
                if(bannerOption.equals("1")){
                    loginAccount.setBannerOption(true);
                }else {
                    loginAccount.setBannerOption(false);
                }
            }

            if(listOption != null){
                if(listOption.equals("1")){
                    loginAccount.setListOption(true);
                }else {
                    loginAccount.setListOption(false);
                }
            }

            loginAccount.setFavouriteCategoryId(favouriteCategoryId);
            loginAccount.setPassword(MD5Util.string2MD5(password));
            loginAccount.setFirstName(firstName);
            loginAccount.setLanguagePreference(languagePreference);
            loginAccount.setLastName(lastName);
            loginAccount.setPhone(phone);
            loginAccount.setState(state);
            loginAccount.setUsername(userName);
            loginAccount.setZip(zip);
            loginAccount.setLanguagePreference(languagePreference);
            loginAccount.setFavouriteCategoryId(favouriteCategoryId);
            loginAccount.setBannerName("<image src=\"images/banner_"+favouriteCategoryId.toLowerCase()+".gif\">");
            accountService.updateAccount(loginAccount);

            loginAccount.setPassword("");
            httpSession.setAttribute("loginAccount",loginAccount);
            return "account/editeAccount";
        }
    }


    private boolean validate(String address1,
                             String address2,
                             String city,
                             String country,
                             String email,
                             String favouriteCategoryId,
                             String password,
                             String repeatedPassword,
                             String firstName,
                             String languagePreference,
                             String lastName,
                             String phone,
                             String state,
                             String userName,
                             String zip){
        if(userName == null || userName.equals("")){
            message = "用户名不能为空";
            return false;
        }
        if(password != null && !password.equals("")){
            if(repeatedPassword == null || repeatedPassword.equals("")){
                message = "请再输入一遍密码";
                return false;
            }
            if(!repeatedPassword.equals(password)){
                message = "两次输入不同";
                return false;
            }
        }
        if(firstName == null || firstName.equals("")){
            message = "firstName不能为空";
            return false;
        }
        if(lastName == null || lastName.equals("")){
            message = "lastName不能为空";
            return false;
        }
        if (email != null && !email.equals("")){
            if (!email.matches("[\\w]+@[\\w]+.[\\w]+[\\w]")) {
                message = "请输入有效的邮箱地址";
                return false;
            }
        } else {
            message = "邮箱不能为空";
            return false;
        }
        if (phone != null && !phone.equals("")){
            if (!phone.matches("^([0-9]{3}-?[0-9]{8}|[0-9]{4}-?[0-9]{7})$")){
                message = "请输入有效的电话号码";
                return false;
            }
        }else{
            message = "电话不能为空";
            return false;
        }
        if(address1 == null || address1.equals("")){
            message = "地址一不能为空";
            return false;
        }
        if(address2 == null || address2.equals("")){
            message = "地址二不能为空";
            return false;
        }
        if(city == null || city.equals("")){
            message = "City不能为空";
            return false;
        }
        if(state == null || state.equals("")){
            message = "State不能为空";
            return false;
        }
        if(zip == null || zip.equals("")){
            message = "Zip不能为空";
            return false;
        }
        if(country == null || country.equals("")){
            message = "Country不能为空";
            return false;
        }
        if (languagePreference == null || languagePreference.equals("")){
            message = "请输入语言偏好";
            return false;
        }
        if (favouriteCategoryId == null || favouriteCategoryId.equals("")){
            message = "请输入类型偏好";
            return false;
        }
        return true;
    }
}
